package com.sky.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.sky.dto.UserLoginDTO;
import com.sky.entity.User;
import com.sky.exception.LoginFailedException;
import com.sky.exception.UserNotLoginException;
import com.sky.mapper.UserMapper;
import com.sky.properties.WeChatProperties;
import com.sky.service.UserService;
import com.sky.utils.HttpClientUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.impl.client.HttpClients;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

/**
 * @author 韩先楚
 */
@Service
@Slf4j
public class UserServiceImpl implements UserService {

    @Autowired
    private WeChatProperties properties;
    @Autowired
    private UserMapper userMapper;

    public static final String WEI_XIN_LOGIN = "https://api.weixin.qq.com/sns/jscode2session";

    /**
     * 微信小程序登录接口
     *
     * @return
     */
    public User login(UserLoginDTO userLoginDTO) {
        //根据code信息调用微信服务器获取其当前用户的openid和session_key
        Map<String, String> map = new HashMap<>();
        map.put("appid",properties.getAppid() );
        map.put("secret",properties.getSecret());
        map.put("js_code",userLoginDTO.getCode());
        map.put("grant_type","authorization_code");
        String s = HttpClientUtil.doGet(WEI_XIN_LOGIN, map);

        JSONObject jsonObject = JSON.parseObject(s);
        String openid = jsonObject.getString("openid");

        //判断openid是否为null ,如果是为mnull 表示登录失败
        if (openid == null)
            throw  new LoginFailedException("登录失败");
        //根据openid判断其是否为新用户
        User userByOpenid = userMapper.getUserByOpenid(openid);
        //如果用户不存在，则创建新用户
        if (userByOpenid == null)
        {
            userByOpenid =User.builder()
                    .openid(openid)
                    .createTime(LocalDateTime.now())
                    .build();
            userMapper.insertUser(userByOpenid);
        }

        return userByOpenid;
    }
}
